﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace Kazuku.Core.Models {
	public class PartialRequest {
		public RouteValueDictionary RouteValues { get; private set; }
		//public NavigationModule NavModule { get; set; }

		public PartialRequest(object routeValues) {
			RouteValues = new RouteValueDictionary(routeValues);
		}

		public void Invoke(ControllerContext context) {
			// TODO: Research whether there's a better way to find the proper route via the provided routeValues
			Route selectedRoute = null;
			foreach (Route route in RouteTable.Routes) {
				if (route.Defaults != null) {
					string controller = route.Defaults["controller"] != null ? route.Defaults["controller"].ToString() : string.Empty;
					string action = route.Defaults["action"] != null ? route.Defaults["action"].ToString() : string.Empty;
					if (controller.ToLower() == RouteValues["controller"].ToString().ToLower() &&
					    action.ToLower() == RouteValues["action"].ToString().ToLower()) {
						selectedRoute = route;
						break;
					}
				}
			}
			
			// This needs to be a route at least within the correct Area, or else the VirtualPathProvider won't look in the right place to find the View.
			RouteData rd = new RouteData(selectedRoute, context.RouteData.RouteHandler);
			
			foreach (var pair in RouteValues) {
				rd.Values.Add(pair.Key, pair.Value);
			}
			IHttpHandler handler = new MvcHandler(new RequestContext(context.HttpContext, rd));
			handler.ProcessRequest(System.Web.HttpContext.Current);
		}

	}
}